﻿using Earthwatchers.Data;
using Earthwatchers.Models;
using Earthwatchers.Models.Portable;
using Earthwatchers.Services.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;

namespace Earthwatchers.Services.Resources
{
    [ServiceContract]
    public class BasecampResource
    {
        private readonly IBasecampRepository basecampRepository;

        public BasecampResource(IBasecampRepository basecampRepository)
        {
            this.basecampRepository = basecampRepository;
        }

        [BasicHttpAuthorization(Role.Admin)]
        [WebGet(UriTemplate = "")]
        public HttpResponseMessage<List<Basecamp>> Get(HttpRequestMessage request)
        {
            try
            {
                return new HttpResponseMessage<List<Basecamp>>(basecampRepository.Get()) { StatusCode = HttpStatusCode.OK };
            }
            catch
            {
                return new HttpResponseMessage<List<Basecamp>>(null) { StatusCode = HttpStatusCode.BadRequest };
            }
        }

        [WebGet(UriTemplate = "/bases")]
        public HttpResponseMessage<List<Basecamp>> GetBaseCamps(HttpRequestMessage request)
        {
            try
            {
                return new HttpResponseMessage<List<Basecamp>>(basecampRepository.GetBaseCamps()) { StatusCode = HttpStatusCode.OK };
            }
            catch
            {
                return new HttpResponseMessage<List<Basecamp>>(null) { StatusCode = HttpStatusCode.BadRequest };
            }
        }

        [BasicHttpAuthorization(Role.Admin)]
        [WebInvoke(UriTemplate = "", Method = "POST")]
        public HttpResponseMessage<Basecamp> Post(Basecamp basecamp, HttpRequestMessage<Basecamp> request)
        {
            if (basecamp != null)
            {
                var basecampDb = basecampRepository.Insert(basecamp);

                var response = new HttpResponseMessage<Basecamp>(basecampDb) { StatusCode = HttpStatusCode.Created };
                return response;
            }
            return new HttpResponseMessage<Basecamp>(null) { StatusCode = HttpStatusCode.NotFound, };
        }

        [BasicHttpAuthorization(Role.Admin)]
        [WebInvoke(UriTemplate = "/del", Method = "POST")]
        public HttpResponseMessage Delete(int id, HttpRequestMessage<int> request)
        {
            if (id != 0)
            {
                basecampRepository.Delete(id);

                return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
            }
            return new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound };
        }
    }
}